﻿//-----------------------------------------------------------------------
// <copyright file="MapperTypeFinder.cs" company="SLWY Enterprises">
// * Copyright (C) 2017 四川商旅无忧科技有限公司 版权所有。
// * version : 1.0
// * author  : qinchaoyue
// * FileName: MapperTypeFinder.cs
// * history : created by qinchaoyue 2017-10-23 12:12:09
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.Linq;
using System.Reflection;
using AutoMapper;
using Slwy.FrameCore.Reflection;

namespace Slwy.FrameCore.Mapping
{
    using Slwy.Utility.DebugLog;

    /// <summary>
    /// mapper 映射文件查找器
    /// </summary>
    public class MapperTypeFinder : IMapSourceTypeFinder
    {
        public MapperTypeFinder()
        {
            AssemblyFinder = new DirectoryAssemblyFinder();
        }

        public IAllAssemblyFinder AssemblyFinder { get; set; }

        public Type[] Find(Func<Type, bool> predicate)
        {
            return this.FindAll().Where(predicate).ToArray();
        }

        public Type[] FindAll()
        {
            try
            {
                var assembliesToScan = this.AssemblyFinder.FindAll();
                return assembliesToScan.SelectMany(a => a.ExportedTypes)
                        .Where(t => typeof(Profile).GetTypeInfo().IsAssignableFrom(t.GetTypeInfo()))
                        .Where(t => !t.GetTypeInfo().IsAbstract)
                        .ToArray();
            }
            catch (Exception e)
            {
                Logs.Err("方法 Slwy.FrameCore.Mapping.MapperTypeFinder.FindAll 错误: " + e);
            }

            return new Type[0];
        }
    }
}
